Java keyboard input [on hold]

Posted by dØd on Game Development See other posts from Game Development or by dØd
Published on 2013-06-28T14:40:35Z Indexed on 2013/06/28 16:31 UTC
Read the original article Hit count: 259

Filed under:
|
|

I'm trying to implement a input system that can detect whether a certain key was held or was only pressed briefly. So far I have this:

KEY_INTERACTION_TRESHOLD = 400ms

//inside a constructor
shouldMeasure = true; 


@Override
public void keyPressed(KeyEvent e) {

    if (shouldMeasure) {
        startTime = System.currentTimeMillis();
        shouldMeasure = false;
        return;
    }
    System.out.println("Button is held down");

    e.consume();
}

@Override
public void keyReleased(KeyEvent e) {

    if (System.currentTimeMillis() - startTime < KEY_INTERACTION_TRESHOLD) {
        System.out.println("Button was only pressed briefly");
    }

    startTime = 0;
    shouldMeasure = true;

    e.consume();
}

Now this works, but the problem is that there is this delay between when I press a key to hold and when the message 'Button is held down' gets displayed. I understand why this delay occurs (for example when you press and hold a letter there will be a similar delay between the first and the second letter printed out), but I would like to somehow avoid it. I'm using only the Java API.

© Game Development or respective owner

Related posts about java

Related posts about input